﻿Imports System.Object
Imports VSModel
Imports Cls_Common
Imports System.IO
Imports SecurityService
Partial Class Control_Contents_Create_News
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function "
    Dim level As String = -1
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Session("KeyWordListId") = Nothing
            getMenu()
            If Not Request.QueryString("type") Is Nothing Then
                hidType.Value = Request.QueryString("type")
            End If
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If


            Dim ctrl As System.Web.UI.WebControls.WebControl
            ctrl = txtContent.CreateCommandButton("ask_mask_fullname", "remove_format.gif", "Bỏ định dạng")
            ctrl.Attributes("onclick") = "removeTextFormat('" + txtContent.ClientID + "');"
            'get the pos after the Italic    
            Dim pos As Integer
            pos = txtContent.ToolControls.IndexOf("JustifyRight") + 1
            'add this custom button into the editor    
            txtContent.InsertToolControl(pos, "ask_mask_fullname", ctrl)



        End If
    End Sub
#End Region
#Region "Event for control "

    Protected Sub getMenu()
        drlMenu.Items.Clear()
        Dim data As New VSEntities
        Dim p As List(Of Menu) = (From q In data.Menus Select q).ToList
        drlMenu.DataValueField = "MenuID"
        drlMenu.DataTextField = "Title"
        RecursiveFillTree(p, 0)
        drlMenu.Items.Insert(0, New ListItem("--- Chọn ---", "0"))
        drlMenu.SelectedValue = Request("MenuId")
    End Sub
    Private Sub RecursiveFillTree(ByVal dtParent As List(Of Menu), ByVal parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()

        For j As Integer = 0 To level - 1
            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If

        Dim data As New VSEntities
        Dim dv As List(Of Menu) = (From q In data.Menus Where q.ParentId = parentID Select q).ToList
        Dim i As Integer

        If dv.Count > 0 Then
            For i = 0 To dv.Count - 1
                Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).Title.ToString()), dv.Item(i).MenuId.ToString())
                If Check_Selected(dv.Item(i).MenuId) = False Then
                    itm.Attributes.Add("class", "ItemDisabled")
                Else
                    itm.Attributes.Add("class", "ItemActived")
                End If
                drlMenu.Items.Add(itm)
                RecursiveFillTree(dtParent, Integer.Parse(dv.Item(i).MenuId.ToString()))
            Next
        End If

        level -= 1
        'on the each function end level will decrement by 1
    End Sub
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            Try
                Dim p As New VSModel.Content
                p.Title = txtTitle.Text.Trim
                p.QueryString = makeURLFriendly(txtTitle.Text.Trim)
                p.Description = txtDescription.Text.Trim
                p.Contents = txtContent.Text.Trim
                p.Author = txtAuthor.Text.Trim
                p.StatusId = 1
                p.MenuId = IIf(drlMenu.SelectedValue = 0, Nothing, CInt(drlMenu.SelectedValue))
                p.IsHot = IIf(chkIsHot.Checked = True, True, False)
                If p.IsHot = True Then
                    p.ImageBig = hidImageBig.Text.Trim
                Else
                    p.ImageBig = Nothing
                End If
                p.Created = Date.Now
                p.Creator = Session("Username")
                p.Modified = Nothing
                p.Modifier = Nothing
                p.Image = hidImagePath.Text.ToString
                p.PublishedDate = Nothing
                p.bEffectiveDate = Nothing
                p.eEffectiveDate = Nothing
                p.IsNew = IIf(chkIsNew.Checked = True, True, False)
                p.TypeId = 1
                data.Contents.AddObject(p)
                data.SaveChanges()
                Dim iContentID As Integer = p.Id
                If (iContentID > 0) Then
                    'Inser KeyWord

                    Dim arrKeyWord As String() = txtKeyword.Text.TrimEnd(";").Split(";")
                    If arrKeyWord.Length > 1 Then
                        For i As Integer = 0 To arrKeyWord.Length - 1
                            Dim q As New ContentsKeyword
                            q.ContentId = iContentID
                            q.KeywordId = arrKeyWord(i)
                            data.ContentsKeywords.AddObject(q)
                            Dim h = (From g In data.Keywords Where g.KeywordID = q.KeywordId Select g).FirstOrDefault
                            h.Viewed = (IIf(IsNothing(h.Viewed) = True, 0, h.Viewed) + 1)
                            data.SaveChanges()
                        Next
                    End If
                    'Insert Subject
                    If txtSubjectId.Text.Trim.TrimEnd(";") <> 0 Then
                        Dim s As New ContentsSubject
                        s.ContentId = iContentID
                        s.SubjectId = txtSubjectId.Text.Trim.TrimEnd(";")

                        data.ContentsSubjects.AddObject(s)
                        data.SaveChanges()
                    End If


                    AddKeyWordJavascript(txtTitle.Text)
                    AddKeyWordJavascript(makeURLFriendly(txtTitle.Text.Trim))

                    Insert_App_Log("Insert Contents:" & txtTitle.Text.Trim & "", Function_Name.Content, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Excute_Javascript("Alertbox('Thêm mới dữ liệu thành công.');window.location ='../../Page/Contents/List.aspx?MenuId=" & drlMenu.SelectedValue & "';", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)

                Excute_Javascript("Alertbox('Cập nhật thất bại.');", Me.Page, True)
            End Try
        End Using

    End Sub
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx?MenuId=" & Request("MenuId"))
    End Sub
#End Region


    Protected Sub hplSelKeyWord_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelKeyWord.Init
        hplSelKeyWord.CssClass = "thickbox"
        hplSelKeyWord.NavigateUrl = "~/Page/KeyWord/KeyWord.aspx?keepThis=true&TB_iframe=true&height=450&width=400&modal=true"
    End Sub

    Protected Sub hplSelSubject_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelSubject.Init
        hplSelSubject.CssClass = "thickbox"
        hplSelSubject.NavigateUrl = "~/Page/Subject/Subject.aspx?keepThis=true&TB_iframe=true&height=450&width=400&modal=true"
    End Sub

End Class
